/*
 * @(#)CookieHandleInterceptor.java $version 2010. 8. 11
 *
 * Copyright 2007-2010 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.nhncorp.usf.core.interceptor.impl;

import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nhncorp.lucy.web.helper.ServletHelper;
import com.nhncorp.lucy.web.interceptor.AbstractInterceptor;
import com.nhncorp.usf.core.config.CookieConfig;
import com.nhncorp.usf.core.util.StringUtil;
import com.nhncorp.usf.core.web.CookieHandler;
import com.nhncorp.usf.core.web.CookieNamePattern;
import com.nhncorp.usf.core.web.DefaultCookieHandler;
import com.nhncorp.usf.core.xwork.ActionInvocationHelper;

import com.opensymphony.xwork.ActionInvocation;

/**
 * @author Web Platform Development Team
 */
public class CookieHandleInterceptor extends AbstractInterceptor implements InterceptorPropertyAware {

    /**
     *
     */
    private static final long serialVersionUID = 8255592546014570111L;

    Log log = LogFactory.getLog(CookieHandleInterceptor.class);

    private Properties properties;

    /**
     * @see com.nhncorp.usf.core.interceptor.impl.InterceptorPropertyAware#setProperties(java.util.Properties)
     * {@inheritDoc}
     */
    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    /**
     * @param invocation the ActionInvocation
     * @return the interceptor result
     * @throws Exception the Exception
     */
    @SuppressWarnings("unchecked")
	public String intercept(ActionInvocation invocation) throws Exception {
        if (properties == null || properties.size() == 0) {
            log.debug("property is blank. execute action invocation.");
            return invocation.invoke();
        }

        CookieConfig cookieConfig = new CookieConfig();
        Enumeration names = properties.propertyNames();

        while (names.hasMoreElements()) {
            String varName = (String)names.nextElement();
            String valueObj = properties.getProperty(varName);

            if (StringUtil.isNotEmpty(varName) && StringUtil.isNotEmpty(valueObj)) {
                cookieConfig.addCookiePattern(new CookieNamePattern(varName, valueObj));
            }
        }

        CookieHandler cookieHandler = new DefaultCookieHandler();
        HttpServletRequest request = ServletHelper.getRequest(invocation);

        Map<String, String> cookieData = cookieHandler.getCookieValues(request.getCookies(), cookieConfig);
        ActionInvocationHelper.getDataMap(invocation).putAll(cookieData);
        return invocation.invoke();
    }

}
